package com.marakana.yamba;

import winterwell.jtwitter.Twitter.Status;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;

public class TimelineActivity extends Activity {

	StatusData statusData;
	SQLiteDatabase db;
	Cursor cursor;
	// TextView textTimeLine;
	ListView listTimeline;
	SimpleCursorAdapter adapter;

	static final String[] from = { StatusData.C_CREATED_AT, StatusData.C_USER,
			StatusData.C_TEXT };

	static final int[] to = { R.id.textCreatedAt, R.id.textUser, R.id.textText };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timeline_basic);
		listTimeline = (ListView) findViewById(R.id.listTimeline);
		// textTimeLine = (TextView) findViewById(R.id.textTimeline);

		// connect to database
		statusData = new StatusData(this);
		db = statusData.getReadableDatabase();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) { //
		case R.id.itemPrefs:
			startActivity(new Intent(this, PrefsActivity.class)); //
			break;

		case R.id.itemServiceStart:
			startService(new Intent(this, UpdaterService.class));
			break;
		case R.id.itemServiceStop:
			stopService(new Intent(this, UpdaterService.class));
			break;
		}
		return true; //
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		db.close();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		cursor = db.query(StatusData.TABLE, null, null, null, null, null,
				statusData.C_CREATED_AT + " DESC");
		startManagingCursor(cursor);
		adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
		listTimeline.setAdapter(adapter);
		// Iterate over all the data and print it out
		// String user, text, output;
		// while (cursor.moveToNext()) { //
		// user = cursor.getString(cursor.getColumnIndex(statusData.C_USER)); //
		// text = cursor.getString(cursor.getColumnIndex(statusData.C_TEXT));
		// output = String.format("%s: %s\n", user, text); //
		// textTimeLine.append(output); //
		// }
	}
}
